package com.xxb.web.aop;

import com.xxb.constant.ResponseCode;
import com.xxb.constant.ResultCode;
import com.xxb.utils.JwtUtil;
import com.xxb.web.dto.ResultJson;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 陈亮
 * @Date: 2018/7/7 19:30
 */
@Aspect
@Component
@Slf4j
public class TokenAop {

    @Pointcut("@annotation(com.xxb.annotation.Token)")
    public void tokenPointCut() {
    }

    @Around("tokenPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        try {
            if (claims != null) {
                return joinPoint.proceed();
            } else {
                return ResultJson.getInstance().setCode(ResponseCode.未授权).setData(null);
            }
        } catch (Throwable throwable) {
            return ResultJson.getInstance().setCode(ResponseCode.未授权).setData(null);
        }
    }

}
